﻿using Microsoft.Extensions.DependencyInjection;
using Vin.Tool.AspNetCore.Singleton;

namespace Vin.Tool.AsyncLocal;

public class AsyncServiceProvider : IAsyncServiceProvider
{
    private readonly AsyncLocal<ServiceProviderHolder> _serviceProvider = new();

    public IServiceProvider? ServiceProvider
    {
        get => _serviceProvider.Value?.ServiceProvider;
        // get => _serviceProvider.Value!.ServiceProvider ??= VinApp.ServiceProvider.CreateScope().ServiceProvider;
        // get
        // {
        //     if (_serviceProvider.Value == null)
        //     {
        //         _serviceProvider.Value = new ServiceProviderHolder()
        //         {
        //             ServiceProvider = VinApp.ServiceProvider.CreateScope().ServiceProvider
        //         };
        //     }
        //     return _serviceProvider.Value?.ServiceProvider;
        // }
        set
        {
            var serviceProviderHolder = _serviceProvider.Value;
            if (serviceProviderHolder != null)
                serviceProviderHolder.ServiceProvider = null;
            if (value == null)
                return;
            _serviceProvider.Value = new ServiceProviderHolder()
            {
                ServiceProvider = value
            };
        }
    }

    private sealed class ServiceProviderHolder
    {
        public IServiceProvider? ServiceProvider;
    }
}